package com.wisecoach.gatewayplus.transaction.tx;

import com.wisecoach.gatewayplus.transaction.SubmitTxContext;
import com.wisecoach.gatewayplus.transaction.SubmittedTxProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * 事务资源，主要由 SubmitTxProducer SubmitTxConsumer SubmitTxBlockListener 使用
 * 资源主要是：
 * 1. 用于记录当前递归深度，用于判断是否需要提交所有交易
 * 2. 记录所有等待提交的交易
 * 3. 记录所有需要确认的交易id
 * {@code @author:} wisecoach
 * {@code @date:} 2023/6/15 下午11:52
 * {@code @version:} 1.0.0
 */


public class SubmitTxResource {

    private final ThreadLocal<Integer> stack = new ThreadLocal<>();

    private final ThreadLocal<List<SubmitTxContext>> txsToCommit = new ThreadLocal<>();

    private final SubmittedTxProcessor submittedTxProcessor;

    public SubmitTxResource(SubmittedTxProcessor submittedTxProcessor) {
        this.submittedTxProcessor = submittedTxProcessor;
    }

    public void push() {
        if (stack.get() == null) {
            stack.set(0);
        }
        stack.set(stack.get() + 1);
    }

    public void pop() {
        stack.set(stack.get() - 1);
    }

    public Integer getStack() {
        Integer stackDeepth = stack.get();
        if (stackDeepth == null) {
            return 0;
        }
        return stackDeepth;
    }

    public void pushTx(SubmitTxContext ctx) {
        List<SubmitTxContext> transactions = txsToCommit.get();
        if (transactions == null) {
            transactions = new ArrayList<>();
            txsToCommit.set(transactions);
        }
        transactions.add(ctx);
    }

    public List<SubmitTxContext> getTxsToCommit() {
        return txsToCommit.get();
    }

    public void clearTxsToCommit() {
        txsToCommit.remove();
    }

    public void pushTxToConfirm(SubmitTxContext ctx) {
        submittedTxProcessor.process(ctx);
    }

}
